package net.ib.mtalk.ui.start;

import java.util.List;

import net.ib.mntalk.protocol.Session.GetSvcAgreementReq;
import net.ib.mntalk.protocol.Session.GetSvcAgreementRes;
import net.ib.mtalk.R;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.global.GlobalPreferences;
import net.ib.mtalk.network.NetFlowControl;
import net.ib.mtalk.network.task.GetSvcAgreementTask;
import net.ib.mtalk.service.SelecterService;
import net.ib.mtalk.ui.HomeActivity;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.CheckBox;
import android.widget.Toast;

/**
 * 약관동의 화면
 * @author urunimi
 *
 */
public class ClauseActivity extends Activity {
	private Context mContext;
	
	private WebView mSvcAgreement;
	private WebView mPersonalPolicy;
	private CheckBox checkClause0;
	private CheckBox checkClause1;
	
	private boolean mIsInstanceCall = false;
	private boolean mFromSetting = false;
	
	private ProgressDialog mProgressDialog;
	
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case HandlerMsgConst.HANDLER_UNKNOWN_ERROR:
				Toast.makeText(mContext, "HANDLER_UNKNOWN_ERROR", Toast.LENGTH_SHORT).show();
				finish();
				break;
			case HandlerMsgConst.HANDLER_GET_SVC_AGREEMENT_SUCCESS:
				Toast.makeText(mContext, "HANDLER_GET_SVC_AGREEMENT_SUCCESS", Toast.LENGTH_SHORT).show();
				GetSvcAgreementRes getSvcAgreementRes = (GetSvcAgreementRes)msg.obj;
				GlobalPreferences.setSvcVersion(getSvcAgreementRes.getVersion());
				loadUrl(getSvcAgreementRes);
				break;
			case HandlerMsgConst.HANDLER_GET_SVC_AGREEMENT_FAIL:
				Toast.makeText(mContext, "HANDLER_GET_SVC_AGREEMENT_FAIL", Toast.LENGTH_SHORT).show();
				finish();
				break;
			default:
				break;
			}
		}
	};
	
	private void loadUrl(GetSvcAgreementRes res)
	{
		mSvcAgreement.loadUrl(res.getSvcagreementUrl());
		mPersonalPolicy.loadUrl(res.getPersonalpolicyUrl());
		
		mSvcAgreement.setWebViewClient(new WebViewClient(){
			public void onPageFinished(WebView view, String url)
			{
				
			}
			
			public void onReceivedError(WebView view, int errorCode, String description, String url)
			{
				AlertDialog dialog = new AlertDialog.Builder(mContext).setMessage(getString(R.string.join_svc_error_msg))
				.setNegativeButton(R.string.ok, new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						finish();
					}
				}).create();
				dialog.setCancelable(false);
				dialog.show();
			}
		});
		
		mPersonalPolicy.setWebViewClient(new WebViewClient(){
			public void onPageFinished(WebView view, String url)
			{
				mProgressDialog.hide();
			}
			
			public void onReceivedError(WebView view, int errorCode, String description, String url)
			{
				AlertDialog dialog = new AlertDialog.Builder(mContext).setMessage(getString(R.string.join_svc_error_msg))
				.setNegativeButton(R.string.ok, new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						finish();
					}
				}).create();
				dialog.setCancelable(false);
				dialog.show();
			}
		});
	}
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_clause);
		
		NetFlowControl.removeAuth();
		
		mContext = this;
		
		mIsInstanceCall = getIntent().getBooleanExtra("changeVersion", false);
		mFromSetting = getIntent().getBooleanExtra("fromSetting", false);
		
		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.setMessage(getString(R.string.waiting));
		mProgressDialog.setCancelable(false);
		
		mSvcAgreement = (WebView) findViewById(R.id.webClause0);
		mPersonalPolicy = (WebView) findViewById(R.id.webClause1);
		
		checkClause0 = (CheckBox) findViewById(R.id.checkClause0);
		checkClause1 = (CheckBox) findViewById(R.id.checkClause1);
		
		if(mFromSetting)
		{
			checkClause0.setVisibility(View.INVISIBLE);
			checkClause1.setVisibility(View.INVISIBLE);
		}
		getSvcAgreement();
	}
	
	private void getSvcAgreement()
	{
		GetSvcAgreementReq getSvcAgreementReq = new GetSvcAgreementReq();
		getSvcAgreementReq.setUserUuid(GlobalPreferences.getUserUUID());
		
		GetSvcAgreementTask task = new GetSvcAgreementTask(mContext, mHandler, getSvcAgreementReq);
		task.execute();
		
		mProgressDialog.show();
	}
	
	public void goToHomeActivity() {
		Intent intent = new Intent(this, HomeActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		finish();
		startActivity(intent);
	}
	
	public void onOkClick(View view) {
		if(mFromSetting)
		{
			finish();
		}
		else if(checkClause0.isChecked() && checkClause1.isChecked()) {
			if(mIsInstanceCall)
			{
				goToHomeActivity();
			}
			else
			{
				startActivity(new Intent(this, AccountTabActivity.class));
				finish();
			}
		} else {
			new AlertDialog.Builder(mContext).setMessage(getString(R.string.join_agree_msg))
			.setNegativeButton(R.string.done, new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			}).create().show();
		}
	}
	
	public void onDestroy()
	{
		super.onDestroy();
		new Handler().postDelayed(new Runnable(){
			public void run() 
			{
				ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
				List<ActivityManager.RunningTaskInfo> info = am.getRunningTasks(50);
				for(int i = 0 ; i < info.size() ; i++)
				{
					if(info.get(i).topActivity.getPackageName().equals(getPackageName()))
						return;
				}
				
				SelecterService.setMode(ClauseActivity.this, SelecterService.Mode.MONO_SELECT);
			}}, 300);
		
		if(mProgressDialog != null)
		{
			mProgressDialog.hide();
			mProgressDialog.dismiss();
		}
	}
	
	public void onResume()
	{
		super.onResume();
		SelecterService.setMode(this, SelecterService.Mode.FULL_SELECT);
	}
}
